package com.mdd.usercenter.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mdd.usercenter.common.BaseResponse;
import com.mdd.usercenter.common.DeleteRequest;
import com.mdd.usercenter.common.ErrorCode;
import com.mdd.usercenter.common.ResultUtils;
import com.mdd.usercenter.exception.BusinessException;
import com.mdd.usercenter.model.domain.User;
import com.mdd.usercenter.model.domain.UserTeam;
import com.mdd.usercenter.model.request.*;
import com.mdd.usercenter.model.vo.TeamUserVo;
import com.mdd.usercenter.service.TeamService;
import com.mdd.usercenter.service.UserService;
import com.mdd.usercenter.model.domain.Team;
import com.mdd.usercenter.service.UserTeamService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/team")
@CrossOrigin(origins = {"http://localhost:3000","http://localhost:8000"},allowCredentials = "true")
public class TeamController {

    @Autowired
    private TeamService teamService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserTeamService userTeamService;


    /**
     * 新增队伍
     * @param teamAddRequest
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addTeam(@RequestBody TeamAddRequest teamAddRequest , HttpSession session) {
        //校验
        if (teamAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //添加
        User loginUser = userService.getLoginUser(session);
        Team team = new Team();
        BeanUtils.copyProperties(teamAddRequest,team);
        Long aLong = teamService.addTeam(team,loginUser);
        if (aLong == null) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"插入失败");
        }
        return ResultUtils.success(aLong);
    }

    /**
     * 删除队伍
     * @param id
     * @return
     */
/*    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTeam(@RequestBody Long id) {
        //校验
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //删除
        boolean res = teamService.removeById(id);
        if (!res) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"删除失败");
        }
        return ResultUtils.success(res);
    }*/

    /**
     * 修改队伍信息
     * @param teamUpdateRequest
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateTeam(@RequestBody TeamUpdateRequest teamUpdateRequest, HttpServletRequest request) {
        //校验
        if (teamUpdateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //更新
        User loginUser = userService.getLoginUser(request.getSession());
        boolean res =  teamService.updateTeam(teamUpdateRequest,loginUser);
        if (!res) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"更新失败");
        }
        return ResultUtils.success(true);
    }

    /**
     * 查询队伍
     * @param
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Team> getTeamList(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = teamService.getById(id);
        if (team == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        return ResultUtils.success(team);

    }

    /**
     * 队伍列表
     * @param teamQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list")
    public BaseResponse<List<TeamUserVo>> getTeamList(TeamQueryRequest teamQueryRequest, HttpServletRequest request) {
        //校验
        if (teamQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //查询
        boolean isAdmin = userService.isAdmin(request);
        User loginUser = null;
        try {
            loginUser = userService.getLoginUser(request.getSession());
        } catch (Exception e) {
            log.info("游客访问");
        }
        List<TeamUserVo> teamList = teamService.getTeamList(teamQueryRequest, isAdmin,loginUser);
        //3.判断当前用户加入了队伍列表中的哪些队列
        //3.1获取每个队列的id
        List<Long> teamIdList = teamList.stream().map(TeamUserVo::getId).collect(Collectors.toList());
        LambdaQueryWrapper<UserTeam> queryWrapper = new LambdaQueryWrapper<>();
        if (loginUser!=null) {
            queryWrapper.eq(UserTeam::getUserId, loginUser.getId()).in(UserTeam::getTeamId, teamIdList);
            //获取当前用户加入的队伍
            List<UserTeam> userTeamList = userTeamService.list(queryWrapper);
            Set<Long> idList = userTeamList.stream().map(UserTeam::getTeamId).collect(Collectors.toSet());
            //遍历teamList
            teamList.forEach(userTeamVo -> {
                //判断当前用户是否加入该队伍
                boolean contains = idList.contains(userTeamVo.getId());
                userTeamVo.setHasJoin(contains);
            });
        }
        //查询每一个队伍的用户信息(人数)
        LambdaQueryWrapper<UserTeam> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.in(UserTeam::getTeamId,teamIdList);
        //查询出队伍列表的所有加入关系
        List<UserTeam> userTeamList = userTeamService.list(queryWrapper1);
        //根据队伍id进行分组
        Map<Long, List<UserTeam>> teamIdUserTeamList = userTeamList.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
        //获取每一个队伍的加入人数
        teamList.forEach(teamUserVo -> {
            teamUserVo.setHasJoinNum(teamIdUserTeamList.get(teamUserVo.getId()).size());
        });
        return ResultUtils.success(teamList);
    }

    /**
     * 队伍分页
     * @param teamQueryRequest
     * @return
     */
    // todo 分页查询
    @GetMapping("/list/page")
    public BaseResponse<Page<Team>> getTeamPage(TeamQueryRequest teamQueryRequest) {
        //校验
        if (teamQueryRequest == null ) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //分页
        Team team = new Team();
        try {
            BeanUtil.copyProperties(teamQueryRequest,team);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        Page<Team> teamPage = new Page<>(teamQueryRequest.getPageNum(),teamQueryRequest.getPageSize());
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>(team);
        Page<Team> page = teamService.page(teamPage, queryWrapper);
        return ResultUtils.success(page);
    }

    /**
     * 加入队伍
     * @param teamJoinRequest
     * @param request
     * @return
     */
    @PostMapping("/join")
    public BaseResponse<Boolean> joinTeam(@RequestBody TeamJoinRequest teamJoinRequest, HttpServletRequest request){
        //校验
        if (teamJoinRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User loginUser = userService.getLoginUser(request.getSession());
        Boolean aBoolean = teamService.joinTeam(teamJoinRequest, loginUser);
        return ResultUtils.success(aBoolean);
    }

    /**
     * 离开队伍
     * @param teamQuitRequest
     * @param request
     * @return
     */
    @PostMapping("quit")
    public BaseResponse<Boolean> quitTeam(@RequestBody TeamQuitRequest teamQuitRequest, HttpServletRequest request){
        //校验
        if (teamQuitRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User loginUser = userService.getLoginUser(request.getSession());
        boolean res =  teamService.quitTeam(teamQuitRequest,loginUser);
        return ResultUtils.success(res);
    }

    /**
     * 队长解散队伍
     * @param deleteRequest
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> disbandTeam(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        //校验
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //删除
        User loginUser = userService.getLoginUser(request.getSession());
        boolean res = teamService.disbandTeam(deleteRequest.getId(),loginUser);
        if (!res) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"删除失败");
        }
        return ResultUtils.success(res);
    }


    /**
     * 获取当前用户创建的队伍
     * @param request
     * @return
     */
    @GetMapping("/list/my/create")
    public BaseResponse<List<Team>> getCreateTeamList(TeamQueryRequest teamQueryRequest,HttpServletRequest request) {
        //查询
        User loginUser = userService.getLoginUser(request.getSession());
        LambdaQueryWrapper<Team> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Team::getUserId,loginUser.getId());
        List<Team> teamList = teamService.list(queryWrapper);
        return ResultUtils.success(teamList);
    }

    /**
     * 获取当前用户加入的队伍
     * @param teamQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list/my/join")
    public BaseResponse<List<TeamUserVo>> getJoinTeamList(TeamQueryRequest teamQueryRequest, HttpServletRequest request) {
        //校验
        if (teamQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //查询
        //获取当前登录用户
        User loginUser = userService.getLoginUser(request.getSession());
        //获取当前用户加入的队伍的ids
        LambdaQueryWrapper<UserTeam> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserTeam::getUserId,loginUser.getId());
        List<UserTeam> list = userTeamService.list(queryWrapper);
        //去重
        Map<Long, List<UserTeam>> map = list.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
        List<Long> ids = new ArrayList<>(map.keySet());
        teamQueryRequest.setIdList(ids);
        List<TeamUserVo> teamList = teamService.getTeamList(teamQueryRequest, true, loginUser);
        return ResultUtils.success(teamList);
    }


}
